package com.tom.joke.view.banner;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.PorterDuff;
import android.graphics.PorterDuffXfermode;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.View;

/**
 * Added by Tom on 2024/07/16.
 * 指示器的小圆点。
 */
public class DotIndicatorView extends View {

    private Drawable drawable;

    public DotIndicatorView(Context context) {
        this(context, null);
    }

    public DotIndicatorView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public DotIndicatorView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        if (drawable != null) {
            /*drawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
            drawable.draw(canvas);*/
            // 画圆形
            Bitmap bitmap = drawableToBitmap(drawable);
            // bitmap 变为圆的。
            Bitmap circleBitmap = getCircleBitmap(bitmap);
            // 圆形bitmap，绘制到画布上。
            canvas.drawBitmap(circleBitmap, 0, 0, null);
        }
    }

    // bitmap 变为圆的。
    private Bitmap getCircleBitmap(Bitmap bitmap) {
        // 创建圆形的bitmap
        Bitmap circleBitmap =  Bitmap.createBitmap(getMeasuredWidth(),
                getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Paint paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setFilterBitmap(true);

        // 绘制圆
        Canvas canvas = new Canvas(circleBitmap);
        canvas.drawCircle(getMeasuredWidth()/2 ,getMeasuredHeight()/2, getMeasuredWidth()/2,paint);
        // 原来的bitmap，绘制到圆上面。  // 取交集（圆形和bitmap矩形的交集）。最后得到圆的bitmap。
        paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
        // 绘制原来的图片。
        canvas.drawBitmap(bitmap, 0, 0, paint);
        bitmap.recycle(); // 回收bitmap
        bitmap = null;
        return circleBitmap;
    }

    /**
     * 7. 把指示器变成圆形
     * 从drawable中得到 bitmap
     *
     * @param drawable
     * @return
     */
    private Bitmap drawableToBitmap(Drawable drawable) {
        if (drawable instanceof BitmapDrawable) {
            return ((BitmapDrawable) drawable).getBitmap();
        }
        // 其他类型：colorDrawable，
        // 创建空bitmap，制造一个bitmap。
        Bitmap outBitmap = Bitmap.createBitmap(getMeasuredWidth(),
                getMeasuredHeight(), Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(outBitmap);

        drawable.setBounds(0, 0, getMeasuredWidth(), getMeasuredHeight());
        drawable.draw(canvas);
        return outBitmap;
    }

    public void setDrawable(Drawable drawable) {
        this.drawable = drawable;
        invalidate(); // 刷新
    }

}
